package com.lottery.im.module.result.ui.game;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.Gravity;
import android.view.View;
import android.widget.GridView;
import android.widget.ProgressBar;
import android.widget.TextView;
import butterknife.BindView;
import butterknife.OnClick;
import com.flyco.tablayout.CommonTabLayout;
import com.flyco.tablayout.listener.CustomTabEntity;
import com.flyco.tablayout.listener.OnTabSelectListener;
import com.lottery.im.R;
import com.lottery.im.api.result.entity.GameHistoryInfo;
import com.lottery.im.api.result.entity.ResultInfo;
import com.lottery.im.base.BaseSwipeFragment;
import com.lottery.im.common.WeakReferenceHandler;
import com.lottery.im.constant.Constants;
import com.lottery.im.constant.RxBusCode;
import com.lottery.im.module.result.adapter.result.item.HorizontalPk30Adapter;
import com.lottery.im.module.result.presenter.GameDetailPresenter;
import com.lottery.im.module.result.ui.good.GetListFragment;
import com.lottery.im.module.result.ui.statistics.BallStatisticsFragment;
import com.lottery.im.module.result.ui.statistics.DoubleStatisticsFragment;
import com.lottery.im.module.result.ui.statistics.LongStatisticsFragment;
import com.lottery.im.module.result.ui.statistics.WinStatisticsFragment;
import com.lottery.im.module.result.view.GameDetailView;
import com.lottery.im.util.TimerUtils;
import com.lottery.im.util.rxbus.RxBus;
import com.lottery.im.view.PkVideoView;
import com.lottery.im.view.ShipVideoView;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

public class GamePkFragment extends BaseSwipeFragment<GameDetailPresenter>
    implements GameDetailView {
  private final static String GAME_TYPE_KEY = "GAME_TYPE_KEY";
  private final static String GAME_TYPE_NAME_KEY = "GAME_TYPE_NAME_KEY";

  public static GamePkFragment create(String gameType, String gameTypeName) {
    GamePkFragment fragment = new GamePkFragment();
    Bundle b = new Bundle();
    b.putString(GAME_TYPE_KEY, gameType);
    b.putString(GAME_TYPE_NAME_KEY, gameTypeName);
    fragment.setArguments(b);
    return fragment;
  }

  @BindView(R.id.tv_title) TextView mTvTitle;
  @BindView(R.id.tv_game_sueId) TextView mTvSueId;
  @BindView(R.id.tv_game_lh) TextView mTvLh;
  @BindView(R.id.tv_he_zhi) TextView mTvHeZhi;
  @BindView(R.id.tv_game_time) TextView mTvTime;
  @BindView(R.id.progressBar) ProgressBar mProgressBar;
  @BindView(R.id.horizontal_list) GridView mHRecyclerView;
  @BindView(R.id.tabLayout) CommonTabLayout mTabLayout;

  @BindView(R.id.pk_video_view) PkVideoView mPkVideoView;
  @BindView(R.id.ship_video_view) ShipVideoView mShipVideoView;

  private String[] mTabNames = { "开奖号码", "双面统计", "长龙统计", "号码分布" };
  private MyCountDownTimer mCountDownTimer;
  private String mGameType;
  private String mGameTypeName;
  private MyHandler mHandler;
  private Timer timer;
  private String isResult;
  private boolean isBegin, isRun;

  @Override protected int getLayoutResId() {
    return R.layout.fragment_game_pk;
  }

  @Override protected void initPresenter() {
    presenter = new GameDetailPresenter(getActivity(), this, this);
    presenter.init();
  }

  @Override public void initView() {
    if (getArguments() == null) {
      popBackStack();
      return;
    } else {
      RxBus.get().register(this);
      mGameType = getArguments().getString(GAME_TYPE_KEY);
      mGameTypeName = getArguments().getString(GAME_TYPE_NAME_KEY);
      mTvTitle.setText(mGameTypeName);
      presenter.queryAllGameTypeResult();
      initTabs();
      if (Constants.shipArr.contains(mGameType)) {
        mPkVideoView.setVisibility(View.GONE);
        mShipVideoView.setVisibility(View.VISIBLE);
      } else {
        mPkVideoView.setVisibility(View.VISIBLE);
        mShipVideoView.setVisibility(View.GONE);
      }
      mHandler = new MyHandler(this);
      timer = new Timer();
      timer.schedule(new TimerTask() {
        @Override
        public void run() {
          if (mHandler != null) {
            Message message = mHandler.obtainMessage(0);
            mHandler.handleMessage(message);
          }
        }
      }, 0, 5000);
      timer.schedule(new TimerTask() {
        @Override
        public void run() {
          if (mHandler != null) {
            Message message = mHandler.obtainMessage(2);
            mHandler.sendMessage(message);
          }
        }
      }, 0, 2000);
      timer.schedule(new TimerTask() {
        @Override
        public void run() {
          if (mHandler != null) {
            Message message = mHandler.obtainMessage(3);
            mHandler.sendMessage(message);
          }
        }
      }, 0, 500);
    }
  }

  @Override public void onDestroy() {
    super.onDestroy();
    RxBus.get().unRegister(this);
    if (mCountDownTimer != null) {
      mCountDownTimer.cancel();
    }
    mCountDownTimer = null;
    mHandler.removeCallbacksAndMessages(null);
    mHandler = null;
    timer.cancel();
  }

  @OnClick({ R.id.iv_back, R.id.btn_anim, R.id.tv_master_plan })
  public void onViewClicked(View view) {
    switch (view.getId()) {
      case R.id.iv_back:
        popBackStack();
        break;
      case R.id.btn_anim:
        mPkVideoView.changeVisible();
        mShipVideoView.changeVisible();
        break;
      case R.id.tv_master_plan://高手计划
        startFragment(new GetListFragment(mGameType));
        break;
    }
  }

  /*
   *  初始化 tab
   * */
  private void initTabs() {
    ArrayList<CustomTabEntity> tabEntities = new ArrayList<>();
    for (int i = 0; i < mTabNames.length; i++) {
      final int position = i;
      tabEntities.add(new CustomTabEntity() {
        @Override public String getTabTitle() {
          return mTabNames[position];
        }

        @Override public int getTabSelectedIcon() {
          return 0;
        }

        @Override public int getTabUnselectedIcon() {
          return 0;
        }
      });
    }
    mTabLayout.setTabData(tabEntities);
    selectTab(0);
    mTabLayout.setOnTabSelectListener(new OnTabSelectListener() {
      @Override public void onTabSelect(int position) {
        selectTab(position);
      }

      @Override public void onTabReselect(int position) {
        selectTab(position);
      }
    });
  }

  public void selectTab(int position) {
    for (int i = 0; i < mTabNames.length; i++) {
      if (i == position) {
        TextView tv = mTabLayout.getTitleView(i);
        tv.setHeight((int) getResources().getDimension(R.dimen.space6));
        tv.setWidth((int) getResources().getDimension(R.dimen.dimen75));
        tv.setGravity(Gravity.CENTER);
        tv.setBackgroundResource(R.drawable.bg_tab_item_result);
      } else {
        TextView tv = mTabLayout.getTitleView(i);
        tv.setHeight((int) getResources().getDimension(R.dimen.space6));
        tv.setWidth((int) getResources().getDimension(R.dimen.dimen75));
        tv.setGravity(Gravity.CENTER);
        tv.setBackgroundResource(0);
      }
    }
    switchFragment(position);
  }

  private void switchFragment(int i) {
    String tag = String.valueOf(i);
    FragmentManager mFragmentManager = getChildFragmentManager();
    Fragment fragment = mFragmentManager.findFragmentByTag(tag);
    FragmentTransaction ft = mFragmentManager.beginTransaction();
    if (fragment == null) {
      switch (i) {
        case 0:
          fragment = WinStatisticsFragment.create(mGameType);
          break;
        case 1:
          fragment = DoubleStatisticsFragment.create(mGameType);
          break;
        case 2:
          fragment = LongStatisticsFragment.create(mGameType);
          break;
        case 3:
          fragment = BallStatisticsFragment.create(mGameType);
          break;
      }
      ft.replace(R.id.container_pk, fragment, tag);
    } else {
      ft.show(fragment);
    }
    ft.commit();
  }

  @Override public void queryHistorySuccess(List<GameHistoryInfo> list) {
  }

  @SuppressLint("SetTextI18n") @Override public void querySuccess(List<ResultInfo> list) {
    for (ResultInfo resultInfo : list) {
      if (mGameType.equals(resultInfo.getGameType())) {
        mTvSueId.setText(resultInfo.getIssueId());
        String resultStr = resultInfo.getResultStr();
        if (resultStr.length() > 0) {
          String[] str = resultStr.split(",");
          if (str.length >= 10) {
            mHRecyclerView.setAdapter(new HorizontalPk30Adapter(getActivity(), Arrays.asList(str)));
            int a1 = Integer.parseInt(str[0]);
            int a2 = Integer.parseInt(str[1]);
            int a3 = Integer.parseInt(str[2]);
            int a4 = Integer.parseInt(str[3]);
            int a5 = Integer.parseInt(str[4]);
            int a6 = Integer.parseInt(str[5]);
            int a7 = Integer.parseInt(str[6]);
            int a8 = Integer.parseInt(str[7]);
            int a9 = Integer.parseInt(str[8]);
            int a10 = Integer.parseInt(str[9]);
            int sum = a1 + a2;
            String lh1;
            String lh2;
            String lh3;
            String lh4;
            String lh5;
            String dx;
            String ds;
            if (a1 > a10) {
              lh1 = "龙";
            } else {
              lh1 = "虎";
            }
            if (a2 > a9) {
              lh2 = "龙";
            } else {
              lh2 = "虎";
            }
            if (a3 > a8) {
              lh3 = "龙";
            } else {
              lh3 = "虎";
            }
            if (a4 > a7) {
              lh4 = "龙";
            } else {
              lh4 = "虎";
            }
            if (a5 > a6) {
              lh5 = "龙";
            } else {
              lh5 = "虎";
            }
            if (sum > 11) {
              dx = "大";
            } else {
              dx = "小";
            }
            if (sum % 2 == 0) {
              ds = "双";
            } else {
              ds = "单";
            }
            mTvLh.setText(lh1 + "    " + lh2 + "    " + lh3 + "    " + lh4 + "    " + lh5);
            mTvHeZhi.setText(sum + "    " + dx + "    " + ds);
          }
        }
        long closeTime = resultInfo.getGMTcloseTime();
        long openTime = resultInfo.getGMTopenTime();
        long curTime = resultInfo.getGMTcurTime();
        isResult = resultInfo.getIsResult();
        mProgressBar.setMax((int) (closeTime - openTime) / 1000);
        if (closeTime - curTime > 0 && "1".equals(isResult)) {
          if (mCountDownTimer != null) {
            mCountDownTimer.cancel();
          }
          mCountDownTimer = new MyCountDownTimer(closeTime - openTime, closeTime - curTime,
              Constants.COUNT_DOWN_INTERVAL);
          mCountDownTimer.start();
          isBegin = false;
          mPkVideoView.setWaitVisible(true);
          mShipVideoView.setWaitVisible(true);
          if (isRun && mPkVideoView.isShow()) {
            mPkVideoView.setResult(resultStr);
            mHandler.postDelayed(() -> {
              if (mHandler != null) {
                Message message = mHandler.obtainMessage(4);
                mHandler.sendMessage(message);
              }
            }, 3000);
            mHandler.postDelayed(() -> {
              if (mHandler != null) {
                Message message = mHandler.obtainMessage(5);
                mHandler.sendMessage(message);
              }
            }, 6000);
            mHandler.postDelayed(() -> {
              Message message = mHandler.obtainMessage(6);
              mHandler.sendMessage(message);
            }, 9000);
            mHandler.postDelayed(() -> {
              if (mHandler != null) {
                Message message = mHandler.obtainMessage(7);
                mHandler.sendMessage(message);
              }
            }, 15000);
          }
          if (isRun && mShipVideoView.isShow()) {
            mShipVideoView.setResult(resultStr);
            mHandler.postDelayed(() -> {
              if (mHandler != null) {
                Message message = mHandler.obtainMessage(4);
                mHandler.sendMessage(message);
              }
            }, 3000);
            mHandler.postDelayed(() -> {
              if (mHandler != null) {
                Message message = mHandler.obtainMessage(5);
                mHandler.sendMessage(message);
              }
            }, 6000);
            mHandler.postDelayed(() -> {
              Message message = mHandler.obtainMessage(6);
              mHandler.sendMessage(message);
            }, 9000);
            mHandler.postDelayed(() -> {
              if (mHandler != null) {
                Message message = mHandler.obtainMessage(7);
                mHandler.sendMessage(message);
              }
            }, 15000);
          }
        } else {
          isBegin = true;
          mPkVideoView.setWaitVisible(false);
          mShipVideoView.setWaitVisible(false);
          mProgressBar.setProgress((int) (closeTime - openTime) / 1000);
          mTvTime.setText(R.string.opening);
          if (mCountDownTimer != null) {
            mCountDownTimer.cancel();
          }
        }
      }
    }
  }

  //根据图片名称取得对应图片
  public int getResourceId(String name) {
    int resID = getResources().getIdentifier(name, "drawable", getActivity().getPackageName());
    //解析资源文件夹下，id为resID的图片
    return resID;
  }

  class MyCountDownTimer extends CountDownTimer {
    private long max;

    public MyCountDownTimer(long max, long millisInFuture,
        long countDownInterval) {
      //微调防止跳过
      super(millisInFuture + millisInFuture * 2 / countDownInterval, countDownInterval);
      this.max = max;
    }

    @Override
    public void onTick(long millisUntilFinished) {
      if (mTvTime == null) return;
      mTvTime.setText(TimerUtils.formatDuring2(millisUntilFinished));
      mPkVideoView.setWaiting(millisUntilFinished / 1000 + "");
      mShipVideoView.setWaiting(millisUntilFinished / 1000 + "");
      mProgressBar.setProgress((int) max / 1000 - (int) millisUntilFinished / 1000);
      isRun = false;
      isBegin = false;
    }

    @Override
    public void onFinish() {
      cancel();
      mTvTime.setText(R.string.opening);
      mPkVideoView.setWaitVisible(false);
      mShipVideoView.setWaitVisible(false);
      isResult = "0";
      isRun = true;
      isBegin = true;
    }
  }

  @SuppressLint("HandlerLeak")
  private class MyHandler extends WeakReferenceHandler<BaseSwipeFragment> {
    public MyHandler(BaseSwipeFragment reference) {
      super(reference);
    }

    protected void handleMessage(BaseSwipeFragment reference, Message msg) {
      switch (msg.what) {
        case 0:
          if (null == mActivity || mActivity.isFinishing()) {
            return;
          }
          if (!"1".equals(isResult)) {
            presenter.queryAllGameTypeResult();
            RxBus.get().send(RxBusCode.REFRESH_CODE);
          } else {
            isRun = false;
          }
          break;
        case 2:
          mPkVideoView.setRunning(isBegin);
          mShipVideoView.setRunning(isBegin);
          break;
        case 3:
          mPkVideoView.setReady();
          break;
        case 4:
          mPkVideoView.setResult2();
          mShipVideoView.setResult2();
          break;
        case 5:
          mPkVideoView.setResult3();
          mShipVideoView.setResult3();
          break;
        case 6:
          mPkVideoView.setResult4();
          mShipVideoView.setResult4();
          break;
        case 7:
          mPkVideoView.setResultGone();
          mShipVideoView.setResultGone();
          isRun = false;
          break;
      }
    }
  }
}
